#ifndef TERMINALWIDGET_H
#define TERMINALWIDGET_H

#include <QWidget>
#include <QPlainTextEdit>
#include <QTextCharFormat>
#include <QFont>
#include <QTimer>
#include <QMap>
#include <QColor>
#include <QQueue>

#include "sshsession.h"

/**
 * @brief 终端模拟器组件
 *
 * 完整的ANSI终端模拟器，支持颜色、光标控制等
 * 提供与真实终端相同的用户体验
 */
class TerminalWidget : public QWidget
{
    Q_OBJECT

public:
    explicit TerminalWidget(QWidget *parent = nullptr);
    ~TerminalWidget();

    // 会话管理
    void setSshSession(SshSession *session);
    void clearSession();
    bool hasSession() const;

    // 终端操作
    void clear();
    void reset();
    void copy();
    void paste();
    void zoomIn();
    void zoomOut();
    void resetZoom();

    // 历史记录
    QStringList getHistory() const;
    void setHistory(const QStringList &history);
    void clearHistory();

    // 配置
    void setFont(const QFont &font);
    void setColors(const QColor &background, const QColor &foreground);
    void setCursorColor(const QColor &color);
    void setScrollbackLines(int lines);

signals:
    void commandExecuted(const QString &command);
    void titleChanged(const QString &title);
    void bell();
    void sessionClosed();

public slots:
    void sendCommand(const QString &command);
    void sendText(const QString &text);
    void sendKey(int key, Qt::KeyboardModifiers modifiers = Qt::NoModifier);

protected:
    void keyPressEvent(QKeyEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseDoubleClickEvent(QMouseEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;
    void focusInEvent(QFocusEvent *event) override;
    void focusOutEvent(QFocusEvent *event) override;
    bool eventFilter(QObject *watched, QEvent *event) override;

private slots:
    void onShellOutput(const QByteArray &data);
    void onShellError(const QByteArray &data);
    void onSessionStateChanged(SshSession::SessionState state);
    void onSelectionChanged();
    void updateCursor();

private:
    // UI组件
    QPlainTextEdit *m_terminalDisplay;

    // SSH会话
    SshSession *m_sshSession;

    // 终端状态
    QString m_currentDirectory;
    QString m_sessionTitle;
    QStringList m_commandHistory;
    int m_historyIndex;
    QString m_commandBuffer;
    int m_cursorPosition;
    bool m_insertMode;

    // ANSI状态
    QTextCharFormat m_currentFormat;
    QTextCharFormat m_defaultFormat;
    QMap<QString, QTextCharFormat> m_textFormats;

    // 光标状态
    QTimer *m_cursorTimer;
    bool m_cursorVisible;
    QColor m_cursorColor;

    // 性能优化
    QTimer *m_updateTimer;
    QString m_pendingText;
    bool m_updatePending;

    // ANSI解析
    void processAnsiEscape(const QByteArray &data);
    void parseAnsiSequence(const QString &sequence);
    void applySgrSequence(const QStringList &params);
    void handleCursorMovement(const QString &sequence);
    void handleScreenClear(const QString &sequence);
    void handleCharacterSet(const QString &sequence);

    // 文本处理
    void appendText(const QString &text, const QTextCharFormat &format = QTextCharFormat());
    void insertTextT(const QString &text, const QTextCharFormat &format = QTextCharFormat());
    void moveCursor(int row, int col);
    void saveCursor();
    void restoreCursor();

    // 命令处理
    void processCommand(const QString &command);
    void executeLocalCommand(const QString &command);
    void executeRemoteCommand(const QString &command);
    void addToHistory(const QString &command);

    // 格式管理
    void initializeFormats();
    void resetFormat();
    QTextCharFormat createFormat(int foreground, int background, bool bold = false, bool italic = false, bool underline = false);

    // 工具方法
    QString getCurrentLine() const;
    void updateDisplay();
    void scrollToBottom();
    bool isCursorAtEnd() const;
    int getScrollbackLines() const;

    // 事件处理
    void handleRemoteKeyPress(QKeyEvent *event);
    void handleLocalKeyPress(QKeyEvent *event);
    void closeSession();

    // 静态颜色表
    static const QColor ansiColors[16];
    static const QColor ansi256Colors[256];
    static const QMap<QString, int> colorNames;
};

#endif // TERMINALWIDGET_H
